package com.warski.wonderfires.dlna.listener;

import android.os.Handler;
import android.os.Message;
import com.warski.wonderfires.dlna.DLNAManager;
import com.warski.wonderfires.dlna.model.DeviceInfo;
import com.warski.wonderfires.dlna.type.EnumDeviceType;
import org.fourthline.cling.model.meta.Device;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by xuhaiping on 2020/9/2.
 */
public class DLNADeviceListener {
    private Handler handler;

    public DLNADeviceListener(){
        handler = new Handler(){
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:
                        onDeviceListRefresh((List<DeviceInfo>)msg.obj);
                        break;
                }
            }
        };
    }

    private List<DeviceInfo> parseDeviceList(Collection<Device> deviceList) {
        final List<DeviceInfo> deviceInfoList = new ArrayList<>();
        for (Device device : deviceList) {
            if (device.findDevices(EnumDeviceType.MediaRenderer.getType()) == null) {
                continue;
            }
            DeviceInfo deviceInfo = new DeviceInfo(device);
            if(DLNAManager.getConnectedDevice() != null &&
                    DLNAManager.getConnectedDevice().getName().compareTo(deviceInfo.getName()) == 0){
                deviceInfoList.add(DLNAManager.getConnectedDevice());
            }
            else {
                deviceInfoList.add(deviceInfo);
            }
        }
        return deviceInfoList;
    }

    public void onDeviceListRefresh(Collection<Device> deviceList){
        Message message = new Message();
        message.what = 1;
        message.obj = parseDeviceList(deviceList);
        handler.sendMessage(message);
    }

    public void onDeviceListRefresh(List<DeviceInfo> deviceList){

    }
}
